home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 60 / IOPROG_60.ISO / soft / c++ / gsl-1.1.1-setup.exe / {app} / src / linalg / balance.c < prev    next >
Encoding:
C/C++ Source or Header  |  2002-04-18  |  1.9 KB  |  85 lines

  1. /* linalg/balance.c
  2.  * 
  3.  * Copyright (C) 2001 Brian Gough
  4.  * 
  5.  * This program is free software; you can redistribute it and/or modify
  6.  * it under the terms of the GNU General Public License as published by
  7.  * the Free Software Foundation; either version 2 of the License, or (at
  8.  * your option) any later version.
  9.  * 
  10.  * This program is distributed in the hope that it will be useful, but
  11.  * WITHOUT ANY WARRANTY; without even the implied warranty of
  12.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13.  * General Public License for more details.
  14.  * 
  15.  * You should have received a copy of the GNU General Public License
  16.  * along with this program; if not, write to the Free Software
  17.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18.  */
  19.  
  20. /* Balance a general matrix by scaling the columns
  21.  *
  22.  * B =  A D
  23.  *
  24.  * where D is a diagonal matrix
  25.  */
  26.  
  27. #include <config.h>
  28. #include <stdlib.h>
  29. #include <gsl/gsl_math.h>
  30. #include <gsl/gsl_vector.h>
  31. #include <gsl/gsl_matrix.h>
  32. #include <gsl/gsl_blas.h>
  33.  
  34. #include <gsl/gsl_linalg.h>
  35.  
  36. int
  37. gsl_linalg_balance_columns (gsl_matrix * A, gsl_vector * D)
  38. {
  39.   const size_t N = A->size2;
  40.   size_t j;
  41.  
  42.   if (D->size != A->size2)
  43.     {
  44.       GSL_ERROR("length of D must match second dimension of A", GSL_EINVAL);
  45.     }
  46.   
  47.   gsl_vector_set_all (D, 1.0);
  48.  
  49.   for (j = 0; j < N; j++)
  50.     {
  51.       gsl_vector_view A_j = gsl_matrix_column (A, j);
  52.       
  53.       double s = gsl_blas_dasum(&A_j.vector);
  54.       
  55.       double f = 1.0;
  56.       
  57.       if (s == 0.0)
  58.         {
  59.           gsl_vector_set (D, j, f);
  60.           continue;
  61.         }
  62.  
  63.       while (s > 1.0)
  64.         {
  65.           s /= 2.0;
  66.           f *= 2.0;
  67.         }
  68.       
  69.       while (s < 0.5)
  70.         {
  71.           s *= 2.0;
  72.           f /= 2.0;
  73.         }
  74.       
  75.       gsl_vector_set (D, j, f);
  76.  
  77.       if (f != 1.0)
  78.         {
  79.           gsl_blas_dscal(1.0/f, &A_j.vector);
  80.         }
  81.     }
  82.  
  83.   return GSL_SUCCESS;
  84. }
  85.